from threading import *
import wx
from Carry import EVT_RESULT,ResultEvent
from string import join,split,strip
import re

# Thread class that executes processing
class LogsThread(Thread):
    """Worker Thread Class."""
    def __init__(self, notify_window,filepath):
        """Init Worker Thread Class."""
        Thread.__init__(self)
        self._notify_window = notify_window
        self.filepath 	 	= filepath
        self.src_regex   	= re.compile(r'SRC=[0-9]+(?:\.[0-9]+){3}')
        self.dst_regex   	= re.compile(r'DST=[0-9]+(?:\.[0-9]+){3}')
        self.proto_regex 	= re.compile(r'PROTO=[a-zA-Z]{3}')
        self.type_regex  	= re.compile(r'\[[a-zA-Z ]+\]') 
        self.start()

    def run(self):
        """Run Worker Thread."""
        logs = self.firewall_logs()
        wx.PostEvent(self._notify_window, ResultEvent({'type':5,'logs':logs}))

    def firewall_logs(self):
        logs = []
        try:
            f = open(self.filepath, "r")
            try:
                src   = ""
                dst   = ""
                proto = ""
                type_ = ""
                data  = ""
                for line in f.readlines():
                    data = line[0:15].strip()
                    try:
                        for reg in self.src_regex.findall(line):
                            src = reg.split('=')[1].strip()
                    except:
                        pass
                    try:
                        for reg in self.dst_regex.findall(line):
                            dst = reg.split('=')[1].strip()
                    except:
                        pass
                    try:
                        for reg in self.proto_regex.findall(line):
                            proto = reg.split('=')[1].strip()
                    except:
                        pass
                    try:
                        for reg in self.type_regex.findall(line):
                            type_ = reg.replace("[","").replace("]","").strip()
                    except:
                        pass
                    logs.append({'DATE':data,'TYPE':type_,'SRC':src,'DST':dst,'PROTO':proto})
            finally:
                f.close()
        except IOError:
            pass

        return logs